<?php

namespace App\Services;
use App\Exceptions\WorkException;
use App\Models\AdminGroup;
use App\Services\BaseServices;
use App\Models\Group;
use App\Util\Code;


class GroupServices extends BaseServices{

    /**
     * 根据分组id获取分组信息
     * @param $groupId
     * @return Group|null|Model|object
     */

    public function getByGroup( $groupId )
    {
        return Group::query()->where('id', $groupId )->first();
    }
    /**
     * 根据用户id获取分组信息
     * @param $groupId
     * @return Group|null|Model|object
     */

    public function getByAdminGroupId( $admin_id )
    {
        return AdminGroup::query()->where('admin_id', $admin_id )->first();
    }
    /**
     * 根据分组id获取分组信息
     * @param $groupIds
     * @return $data|Group|null|Model|Object|
     */

    public function getByGroups( $groupIds )
    {

        $data =  Group::query( )->whereIn('id', $groupIds )->get();

        if ( is_null( $data ) || $data->count() !== count($groupIds) ){
            throw new WorkException(Code::GROUP_NOT_ILLEGAL );
        }

        return $data;

    }
    /**
     * 批量创建用户对应分组表
     * @param $groupIds
     * @return $data|AdminGroup|null|Model|Object|
     */
    public function CreateByAdminGroup( $admin_id,$groupIds )
    {

        $data = [];
        foreach ($groupIds as $key=>$val){

            $data[$key]['admin_id'] = $admin_id;
            $data[$key]['group_id'] = $val;
        }

        return AdminGroup::query()->insert($data);
    }
    /**
     * 批量修改用户对应分组表
     * @param $groupIds
     * @return $data|AdminGroup|null|Model|Object|
     */
    public function UpdateByAdminGroup( $admin_id , $groupIds )
    {
        $data = $this -> getByGroups( $groupIds );

        AdminGroup::where('admin_id', $admin_id )->delete();

        return $this -> CreateByAdminGroup( $admin_id, $groupIds );
    }
}